package cn.melonlib.security.encryption.comp.enc;

import cn.hutool.core.codec.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${spring.security.user.name:''}")
    private String user;
    @Value("${spring.security.user.password:''}")
    private String password;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().logout().permitAll();
    }
    private static final Pattern authRegex=Pattern.compile("^.*Basic (.+)$");
    public Boolean auth(String auth){
        if(StringUtils.isBlank(auth)){
            return false;
        }
        try {
            Matcher m=authRegex.matcher(auth);
            if(m.matches()){
                return new String(Base64.decode(m.group(1)), StandardCharsets.UTF_8).equals(user+":"+password);
            }else{
                return false;
            }
        }catch (Exception e){
            return false;
        }
    }

}
